﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using ComLib.ComType;
using System.Threading.Tasks;
using CoreBroker;
using KWindow.KPageCore;
using Newtonsoft.Json.Linq;
using LogLib;
using HZWebService.Models;
using HZWebService;
using System.Windows.Forms;
using EECMISWS;
using ComUIControl;

namespace IPCPages
{
    public class ProcessUploading : PageProcessBase<ProcessUploading>
    {
        private TransferControl _transfer_crj = null;

        private TransferControl _transfer_jg = null;

        /// <summary>
        /// 选中的照片
        /// </summary>
        private TakenPhoto _thePhoto = null;

        private bool _uploadResult = false;

        private string crjPhotoSaveDir = "D:\\Crj_Photo";
        private string jgPhotoSaveDir = "D:\\Jg_Photo";

        private ProcessUploading() : base()
        {

        }

        public override void Init()
        {
            base.Init();
        }

        public override void Exit()
        {
            base.Exit();
        }

        public override void InitData()
        {
            _uploadResult = false;
            _thePhoto = GetValue<TakenPhoto>("TakenPhoto");
            if (_thePhoto == null)
            {
                Log.WriteAsync("发生了意外的错误:\n 获取选中照片失败。");
                MsgBox.Show("发生了意外的错误:\n 获取选中照片失败。");
                NotifyClientTakePhotoAborted("发生了意外的错误:\n 获取选中照片失败。");
                ToHome();
                return;
            }
            base.InitData();
            //CreatTransfer();
        }

        private void NotifyClientTakePhotoAborted(string reason)
        {
            if (Job != null)
            {
                Job.Abort(reason);
            }
        }

        public override void UpdateData()
        {
            base.UpdateData();
            SetValue("UploadResult", _uploadResult);
        }

        public override void ClearData()
        {
            base.ClearData();
            for (int i = 0; i < Pages.Count; i++)
            {
                Pages[i].ClearData();
            }
            if (_transfer_jg != null)
            {
                _transfer_jg.Dispose();
                _transfer_jg = null;
            }
            _thePhoto = null;
        }

        public override void StartWork()
        {
            base.StartWork();
            BeginUploading();
        }

        public override void StopWork()
        {
            base.StopWork();
        }

        public override void PlayWelcomeVoice()
        {
            base.PlayWelcomeVoice();
        }

        private void CreatTransfer()
        {
            _transfer_jg = new TransferControl("FTPService_JG");
            //_transfer = new TransferControl("FTPService");
            _transfer_jg.OnCatchException = OnCatchException;
            _transfer_jg.OnPostOK = OnUploadCompleted;
            _transfer_jg.OnPostFailed = OnUploadFailed;
            _transfer_jg.OnTimeout = OnUploadingTimeout;
            _transfer_jg.OnLoginOK = OnFtpLoginOk;
            _transfer_jg.OnLoginFailed = OnFtpLoginFail;
            _transfer_jg.Init();

            _transfer_crj = new TransferControl("FTPService_CRJ");
            //_transfer = new TransferControl("FTPService");
            _transfer_crj.OnCatchException = OnCatchException;
            _transfer_crj.OnPostOK = OnUploadCompleted;
            _transfer_crj.OnPostFailed = OnUploadFailed;
            _transfer_crj.OnTimeout = OnUploadingTimeout;
            _transfer_crj.OnLoginOK = OnFtpLoginOk;
            _transfer_crj.OnLoginFailed = OnFtpLoginFail;
            _transfer_crj.Init();
        }

        private string CreateTodayDir(string baseDir)
        {
            string path = string.Format("{0}\\{1}\\{2}", baseDir, DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("dd"));
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
                Log.WriteAsync("创建照片目录:" + path);
            }
            return path;
        }

        private void SavePhotoToLocalDir(ApplyTo applyTo, string id, string photoPath, bool toNext)
        {
            string path = "";
            switch (applyTo)
            {
                case ApplyTo.ExitAndEntry:    //出入境
                case ApplyTo.PortVisa:    //出入境
                    path = CreateTodayDir(crjPhotoSaveDir);
                    break;
                case ApplyTo.DrivingLicence:  //交管
                    path = CreateTodayDir(jgPhotoSaveDir);
                    break;
                default:
                    break;
            }
            string destFile = $"{path}\\{id}.jpg";
            try
            {              
                if (!string.IsNullOrEmpty(path) && File.Exists(photoPath))
                {                   
                    File.Copy(photoPath, destFile, true);
                    Log.WriteAsync($"文件从{photoPath}复制到{destFile}成功.");
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(ex.ToString());
                MsgBox.Show($"复制照片{photoPath}到{destFile}发生了异常：{ex.Message}");
                return;
            }           
            if (toNext)
            {
                OnUploadCompleted("上传完成");
            }
        }

        private void BeginUploading()
        {
            JObject args = new JObject();
            IDCardAll cardInfo = GetValue<IDCardAll>("IDCardInfo");
            if (cardInfo != null)
            {
                args["SFZH"] = cardInfo.number;
                args["PersonName"] = cardInfo.name;
            }
            else
            {
                args.Add("SFZH", "");
                args.Add("PersonName", "");
            }
            string photoSN = GetValue<string>("PhotoSerialNumber");
            args["PhotoName"] = photoSN;
            args["OrigPhotoPath"] = _thePhoto.SourceImagePath;
            args["DestPhotoPath"] = _thePhoto.DestImagePath;
            ApplyTo applyTo = GetValue<ApplyTo>("ApplyTo");

            Task.Run(() =>
            {
                switch (applyTo)
                {
                    case ApplyTo.ExitAndEntry:    //出入境                       
                        UploadCrjService(args.ToString(), cardInfo.number, _thePhoto.DestImagePath);
                        break;
                    case ApplyTo.IDCard:          //户政
                        UploadHzService(cardInfo.number, _thePhoto.DestImagePath);
                        break;
                    case ApplyTo.DrivingLicence:  //交管
                        UploadJGService(photoSN, _thePhoto.DestImagePath);
                        break;
                    default:
                        UploadCrjService(args.ToString(), photoSN, _thePhoto.DestImagePath);
                        break;
                }
            });         
        }

        private void UploadJGService(string id, string path)
        {
            //_transfer_jg.Login();
            SavePhotoToLocalDir(ApplyTo.DrivingLicence, id, path, true);
        }

        private void OnFtpLoginOk(string outParams)
        {
            Log.WriteAsync("FTP登录成功");
            //登录成功，开始上传
            JObject args = new JObject();
            args["PhotoName"] = GetValue<string>("PhotoSerialNumber");
            args["OrigPhotoPath"] = _thePhoto.SourceImagePath;
            args["DestPhotoPath"] = _thePhoto.DestImagePath;
            _transfer_jg.Post(args.ToString());
        }

        private void OnFtpLoginFail(string outParams)
        {
            Log.WriteAsync("FTP登录失败");
            OnUploadFailed("照片上传失败！交管FTP登录失败");
        }

        private void UploadHzService(string id, string path)
        {
            WebInterface hzInterface = new WebInterface();
            if (hzInterface.Enabled)
            {
                HzPhotoResponeArg response = new HzPhotoResponeArg();
                string msg = "";
                if (hzInterface.UploadPhoto(id, path, out response, out msg))
                {
                    if (response != null)
                    {
                        if (response.success)
                        {
                            if (response.result.Count > 0)
                            {
                                if (response.result[0].stateCode)  //
                                {
                                    OnUploadCompleted("户政接口上传成功");
                                }
                                else
                                {
                                    OnCheckFailed(response.result[0].info);
                                }
                            }
                            else
                            {
                                OnCheckFailed("检测平台返回结果明细为空");
                            }
                        }
                        else
                        {
                            OnCheckFailed(response.desc);
                        }
                    }
                    else
                    {
                        OnCheckFailed("检测平台返回结果为空");
                    }
                }
                else
                {
                    OnUploadFailed(msg);
                }
            }
            else
            {
                Log.WriteAsync("设置为不上传户政接口");
                OnUploadCompleted("设置为不上传户政接口");
            }
        }
        private void UploadCrjService(string json, string id, string photoPath)
        {
            WebDataAccess webAccess = WebDataAccess.Instance;
            if (webAccess.Enabled)
            {
                if (!webAccess.Inited)
                {
                    if (!webAccess.Login())
                    {
                        OnUploadFailed(webAccess.ErrorMessage);
                        return;
                    }
                }
                string outMsg = "";
                if (webAccess.Post(json, out outMsg))
                {
                    SavePhotoToLocalDir(ApplyTo.ExitAndEntry, id, photoPath, false);
                    OnUploadCompleted(outMsg);
                    return;
                }
                else
                {
                    OnUploadFailed(webAccess.ErrorMessage);
                    return;
                }
            }
            else
            {
                SavePhotoToLocalDir(ApplyTo.ExitAndEntry, id, photoPath, true);
                Log.WriteAsync("设置为不上传出入境接口");
            }

            //else
            //{
            //    _transfer.PostAll(json);
            //}
        }

        public event Action<string> UploadFailed = null;
        private void OnUploadFailed(string outParams)
        {
            string msg = string.Format("照片上传失败: \n{0}", outParams);
            Log.WriteAsync(msg);
            Action<string> handler = (e) =>
            {
                //StopWork();
                ClearData();
                UploadFailed?.Invoke(msg);
            };
            MainPage.Invoke(handler, msg);                   
        }

        private void OnUploadCompleted(string outParams)
        {
            _uploadResult = true;
            string msg = $"上传结果: \n{outParams}";
            Log.WriteAsync(msg);
            Action handler = () =>
            {
                UpdateData();
                ClearData();
                if (IsRunning)
                {
                    ToNext();
                }
            };
            MainPage.Invoke(handler);         
        }

        private void OnCheckFailed(string outParams)
        {
            string msg = string.Format("照片监测不通过:{0}", outParams);
            Log.WriteAsync(msg);
            Action<string> handler = (e) =>
            {
                //StopWork();
                ClearData();
                UploadFailed?.Invoke(msg);
            };
            MainPage.Invoke(handler, msg);
        }

        private void OnUploadingTimeout(string outParams)
        {
            string msg = string.Format("提交数据超时: \n{0}", outParams);
            Log.WriteAsync(msg);
            Action<string> handler = (e) =>
            {
                //StopWork();
                ClearData();
                UploadFailed?.Invoke(msg);
            };
            MainPage.Invoke(handler, msg);
        }

        private void OnCatchException(string outParams)
        {
            string msg = string.Format("提交数据时发生了异常: \n{0}", outParams);
            Log.WriteAsync(msg);
            Action<string> handler = (e) =>
            {               
                //StopWork();
                ClearData();
                UploadFailed?.Invoke(msg);
            };
            MainPage.Invoke(handler, msg);
        }
    }
}
